import {Component, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams,ToastController} from 'ionic-angular';
import {LoadingService} from "../../../services/common/loading.service";
import {SideMenuService} from "../../../services/common/side-menu.service";
import {TimeUtil} from "../../../model/util/TimeUtil";
import {TeamOverviewProvider} from "../../../providers/perfomance/team-overview/team-overview-provider";
import {HistoricalPerformanceProvider} from "../../../providers/perfomance/historical-performance/historical-performance.provider";
import {ToastService} from '../../../services/common/toast.service';

@IonicPage()
@Component({
    selector:'page-team-performance-overview',
    templateUrl:'team-performance-overview.html',
    providers:[
        SideMenuService,
        LoadingService,
        TeamOverviewProvider,
        HistoricalPerformanceProvider,
        ToastService
    ]
})

export class TeamPerformanceOverviewPage {
    @ViewChild(Content) content: Content;

    //当前显示tab；
    private currentView = 0;
    private isLoaded:boolean = false;

    private teamOverData = {};
    private agentCode = localStorage.getItem('userName');
    //开始时间
    private startFilterDate = '';
    //结束时间
    private endFilterDate = '';
    //筛选时间
    private  filterDate = '';
    //首次加载分组数据
    private isLoadData:boolean = true;
    //首次加载历史数据
    private isLoadData2:boolean = true;
    //分组业绩
    private groupList = [];
    //历史数据
    private hisPerData;

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        private load:LoadingService,
        private sideMenuService: SideMenuService,
        private teamOverViewProvider:TeamOverviewProvider,
        private toastController:ToastController,
        private hisPerProvider: HistoricalPerformanceProvider,
        private toastService:ToastService
    ){}

    ionViewDidLoad() {

        //初始化时间范围（当月）
        this.startFilterDate = TimeUtil.getLocalTime(Date.now());
        this.endFilterDate = TimeUtil.getLocalTime(Date.now());

        this.getTeamOverViewData();
    }

    /**
     * 获取团队历史业绩
     */
    getGroupHistoricalPer() {
        this.isLoaded = false;
        this.load.showLoading();
        this.hisPerProvider.getHistoricalPer().subscribe((res) => {
            this.hisPerData = res;
            this.isLoaded = true;
            this.load.dismissLoading();
        },err=>{
            this.load.dismissLoading();
            if(err.status==500){
                // this.toastService.showToast('请求失败')
            }
        })
    }

    /**
     * 点击进入主管成员历史业绩列表
     * @{param} {type:0--直辖组；1--所辖组}
     */
    goToMemberPerformance(id,type) {
        this.navCtrl.push('MemberPerformancePage', {'groupId':id,"groupType":type});
    }

    /**
     * 分组业绩查询
     */
    filter(){
        if (this.endFilterDate != '' && this.startFilterDate != '' && this.endFilterDate < this.startFilterDate) {
            let toast = this.toastController.create({
                message: '结束时间不能早于开始时间，请重新选择',
                duration: 2000,
                position: 'middle'
            });
            toast.present();
            return;
        }
        this.isLoaded = false;
        this.load.showLoading();
        this.teamOverViewProvider.getGroupList(this.startFilterDate,this.endFilterDate).subscribe(r=>{
            this.load.dismissLoading();
            this.isLoaded = true;
            this.groupList = r;
        },err=>{
            this.load.dismissLoading();
            if(err.status==500){
                // this.toastService.showToast('请求失败')
            }
            this.isLoaded = true;
        });
        console.log('filter');
    }

    /**
     * 获取业绩总览
     */
    getTeamOverViewData(){
        this.load.showLoading();
        this.teamOverViewProvider.getTeamOverViewData().subscribe(r=>{
            this.teamOverData = r;
            console.log(r);
            setTimeout(()=>{
                this.calcDirectBarWidth()
            },500);
            this.load.dismissLoading();
        },(err=>{
            this.load.dismissLoading();
            if(err.status==500){
                // this.toastService.showToast('请求失败')
            }
        }));
    }

    /**
     * 业绩总览柱状图长度计算
     *
     */
    calcDirectBarWidth(){
        let maxWidth=41,direct,directNormal=true,under,underNormal=true;
        // 直辖组
        if(Number(this.teamOverData['directYearPC'])>Number(this.teamOverData['directHighestPC'])){
            direct=this.teamOverData['directYearPC'];
            directNormal=false;
        }else{
            direct=this.teamOverData['directHighestPC'];
        }

        if(this.teamOverData['directMonthPC']&&Number(this.teamOverData['directMonthPC'])){
            let value=Number(this.teamOverData['directMonthPC'])/direct*maxWidth+'vw';
            $('#direct-month').animate({width:value},300,'swing')
        }

        if(this.teamOverData['directYearPC']&&Number(this.teamOverData['directYearPC'])){
            let value=Number(this.teamOverData['directYearPC'])/direct*maxWidth+'vw';
            $('#direct-year').animate({width:value},directNormal?400:500,'swing')
        }

        if(this.teamOverData['directHighestPC']&&Number(this.teamOverData['directHighestPC'])){
            let value=Number(this.teamOverData['directHighestPC'])/direct*maxWidth+'vw';
            $('#direct-hisYear').animate({width:value},directNormal?400:500,'swing')
        }

        // 所辖组
        if(Number(this.teamOverData['underYearPC'])>Number(this.teamOverData['underHighestPC'])){
            under=this.teamOverData['underYearPC'];
            underNormal=false;
        }else{
            under=this.teamOverData['underHighestPC'];
        }

        if(this.teamOverData['underMonthPC']&&Number(this.teamOverData['underMonthPC'])){
            let value=Number(this.teamOverData['underMonthPC'])/under*maxWidth+'vw';
            $('#under-month').animate({width:value},300,'swing')
        }

        if(this.teamOverData['underYearPC']&&Number(this.teamOverData['underYearPC'])){
            let value=Number(this.teamOverData['underYearPC'])/under*maxWidth+'vw';
            $('#under-year').animate({width:value},underNormal?400:500,'swing')
        }

        if(this.teamOverData['underHighestPC']&&Number(this.teamOverData['underHighestPC'])){
            let value=Number(this.teamOverData['underHighestPC'])/under*maxWidth+'vw';
            console.log(value);
            $('#under-hisYear').animate({width:value},underNormal?400:500,'swing')
        }
    }

    /**
     * 跳转到分组列表
     * @param {any} item
     */
    goToGroupMember(item:any){
        this.navCtrl.push('TeamPerformanceDetailPage',{
            groupID:item.groupID ||item.groupId,
            groupName:item.groupName,
            type:2,
            startFilterDate:this.startFilterDate,
            endFilterDate:this.endFilterDate
        });
    }

    /**
     * 点击tab切换
     */
    chooseView(num) {
        if(num === 1){
            if(this.isLoadData){//获取分组数据
                this.isLoadData = false;
                this.filter();
            }
        }else if(num === 2){
            if(this.isLoadData2){//获取历史数据
                this.isLoadData2 = false;
                this.getGroupHistoricalPer();
            }
        }
        this.currentView = num;
        if(!num){
            setTimeout(()=>{
                this.calcDirectBarWidth();
            },100);
        }
    }

    /**
     * 返回
     * @param ev
     */
    backButtonClick(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.navCtrl && this.navCtrl.pop(null, null);
    }

    /**
     * 移至顶部
     */
    goUp() {
        this.content.scrollToTop();
    }
}
